<!-- src/views/teacher/StudentManagement.vue -->
<template>
  <div class="student-management">
    <div class="header">
      <el-page-header @back="$router.go(-1)" title="返回">
        <template #content>
          <span class="title">学生管理</span>
        </template>
      </el-page-header>
    </div>

    <el-card class="filter-card">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
            v-model="searchParams.keyword"
            placeholder="搜索学生姓名或学号"
            clearable
            @clear="resetSearch"
            @keyup.enter="fetchStudents"
          >
            <template #append>
              <el-button icon="Search" @click="fetchStudents" />
            </template>
          </el-input>
        </el-col>

        <el-col :span="6">
          <el-select
            v-model="searchParams.internshipStatus"
            placeholder="实习状态"
            clearable
            @change="fetchStudents"
          >
            <el-option label="全部" value="" />
            <el-option label="未开始" :value="0" />
            <el-option label="进行中" :value="1" />
            <el-option label="已完成" :value="2" />
            <el-option label="已终止" :value="3" />
          </el-select>
        </el-col>

        <el-col :span="6">
          <el-button @click="resetSearch">重置</el-button>
        </el-col>
      </el-row>
    </el-card>

    <el-card>
      <el-table
        :data="students"
        v-loading="loading"
        style="width: 100%"
      >
        <el-table-column prop="studentNumber" label="学号" width="120">
          <template #default="scope">
            {{ scope.row.studentId }}
          </template>
        </el-table-column>
        <el-table-column prop="studentName" label="姓名" width="100" />
        <el-table-column prop="companyName" label="实习企业" width="150" />
        <el-table-column prop="positionTitle" label="实习岗位" width="120" />
        <el-table-column prop="mentorName" label="企业导师" width="100" />
        <el-table-column prop="mentorPhone" label="导师电话" width="120" />
        <el-table-column prop="mentorEmail" label="导师邮箱" width="180" />
        <el-table-column label="实习状态" width="100">
          <template #default="scope">
            <el-tag :type="getInternshipStatusType(scope.row.status)">
              {{ getInternshipStatusLabel(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="viewStudentDetails(scope.row)">查看详情</el-button>
            <el-dropdown v-if="scope.row.status !== 2 && scope.row.status !== 3" @command="(command) => handleStatusChange(scope.row, command)">
              <el-button size="small" type="primary">
                状态管理<el-icon class="el-icon--right"><arrow-down /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item
                    v-if="scope.row.status === 0"
                    :command="1"
                  >
                    开始实习
                  </el-dropdown-item>
                  <el-dropdown-item
                    v-if="scope.row.status === 1"
                    :command="2"
                  >
                    结束实习
                  </el-dropdown-item>
                  <el-dropdown-item
                    v-if="scope.row.status === 1"
                    :command="3"
                  >
                    终止实习
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :total="pagination.total"
        layout="total, prev, pager, next, jumper"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
        class="pagination"
      />
    </el-card>

    <!-- 学生详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="学生详情"
      width="700px"
    >
      <div v-if="selectedStudent" class="student-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="学号">{{ selectedStudent.studentId }}</el-descriptions-item>
          <el-descriptions-item label="姓名">{{ selectedStudent.studentName }}</el-descriptions-item>
          <el-descriptions-item label="实习企业">{{ selectedStudent.companyName }}</el-descriptions-item>
          <el-descriptions-item label="实习岗位">{{ selectedStudent.positionTitle }}</el-descriptions-item>
          <el-descriptions-item label="企业导师">{{ selectedStudent.mentorName }}</el-descriptions-item>
          <el-descriptions-item label="导师电话">{{ selectedStudent.mentorPhone }}</el-descriptions-item>
          <el-descriptions-item label="导师邮箱">{{ selectedStudent.mentorEmail }}</el-descriptions-item>
          <el-descriptions-item label="开始日期">{{ formatDate(selectedStudent.startDate) }}</el-descriptions-item>
          <el-descriptions-item label="结束日期">{{ formatDate(selectedStudent.endDate) }}</el-descriptions-item>
          <el-descriptions-item label="实习状态">
            <el-tag :type="getInternshipStatusType(selectedStudent.status)">
              {{ getInternshipStatusLabel(selectedStudent.status) }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useTeacherStore } from '../../store/teacher'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { ArrowDown } from '@element-plus/icons-vue'

const teacherStore = useTeacherStore()
const router = useRouter()

const students = ref([])
const loading = ref(false)
const detailDialogVisible = ref(false)
const selectedStudent = ref(null)

// 搜索参数
const searchParams = reactive({
  keyword: '',
  internshipStatus: ''
})

// 分页参数
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 获取学生列表（实际是获取指导的实习列表）
const fetchStudents = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.currentPage - 1,
      size: pagination.pageSize,
      ...searchParams
    }

    const response = await teacherStore.getGuidedInternships(params)
    students.value = response.content || response
    pagination.total = response.totalElements || 0
  } catch (error) {
    ElMessage.error('获取学生列表失败: ' + (error.response?.data?.message || error.message))
  } finally {
    loading.value = false
  }
}

// 重置搜索
const resetSearch = () => {
  searchParams.keyword = ''
  searchParams.internshipStatus = ''
  pagination.currentPage = 1
  fetchStudents()
}

// 分页处理
const handleCurrentChange = (page) => {
  pagination.currentPage = page
  fetchStudents()
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.currentPage = 1
  fetchStudents()
}

// 查看学生详情
const viewStudentDetails = async (internship) => {
  try {
    const response = await teacherStore.getInternshipDetail(internship.id)
    selectedStudent.value = response
    detailDialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取学生详情失败: ' + (error.response?.data?.message || error.message))
  }
}

// 处理实习状态变更
const handleStatusChange = (internship, status) => {
  const statusLabel = getInternshipStatusLabel(status)

  ElMessageBox.confirm(
    `确定要将实习状态变更为"${statusLabel}"吗？`,
    '确认操作',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await teacherStore.updateInternshipStatus(internship.id, status)
      ElMessage.success(`实习状态已更新为"${statusLabel}"`)
      fetchStudents()
    } catch (error) {
      ElMessage.error('操作失败: ' + (error.response?.data?.message || error.message))
    }
  }).catch(() => {
    // 用户取消操作
  })
}

// 获取实习状态标签
const getInternshipStatusLabel = (status) => {
  switch (status) {
    case 0: return '未开始'
    case 1: return '进行中'
    case 2: return '已完成'
    case 3: return '已终止'
    default: return '未知'
  }
}

// 获取实习状态类型
const getInternshipStatusType = (status) => {
  switch (status) {
    case 0: return ''
    case 1: return 'primary'
    case 2: return 'success'
    case 3: return 'danger'
    default: return ''
  }
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString()
}

onMounted(() => {
  fetchStudents()
})
</script>

<style scoped>
.header {
  margin-bottom: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.student-detail {
  margin-bottom: 20px;
}

.internship-section {
  margin-top: 20px;
}

.internship-section h3 {
  margin-bottom: 10px;
}
</style>
